package asia.doing.controller.admin;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import asia.doing.common.Result;
import asia.doing.common.enums.ResultCodeEnum;
import asia.doing.common.enums.RoleEnum;
import asia.doing.entity.Account;
import asia.doing.service.admin.ManageAdminService;
import asia.doing.service.admin.ManageUserService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * 基础前端接口
 */
@RestController
public class WebController {

    @Resource
    private ManageAdminService manageAdminService;

    @Resource
    private ManageUserService manageUserService;

    @GetMapping("/")
    public Result hello() {
        return Result.success("访问成功");
    }

    /**
     * 登录
     */
    @PostMapping("/login")
    public Result login(@RequestBody Account account) {
        System.out.println("我拿到了账户:" + account.getName() + account.getRole());
        if (ObjectUtil.isEmpty(account.getUsername()) || ObjectUtil.isEmpty(account.getPassword())
                || ObjectUtil.isEmpty(account.getRole())) {
            return Result.error(ResultCodeEnum.PARAM_LOST_ERROR);
        }
        if (RoleEnum.ADMIN.name().equals(account.getRole())) {
            System.out.println("我进入了后台用户登录页面");
            account = manageAdminService.login(account);
        } else if (RoleEnum.USER.name().equals(account.getRole())){
            System.out.println("我进入了前台用户登录页面");
            account = manageUserService.login(account);
        }
        return Result.success(account);
    }

    /**
     * 注册
     */
    @PostMapping("/register")
    public Result register(@RequestBody Account account) {
        if (StrUtil.isBlank(account.getUsername()) || StrUtil.isBlank(account.getPassword())
                || ObjectUtil.isEmpty(account.getRole())) {
            return Result.error(ResultCodeEnum.PARAM_LOST_ERROR);
        }
        if (RoleEnum.ADMIN.name().equals(account.getRole())) {
            manageAdminService.register(account);
        } else if (RoleEnum.USER.name().equals(account.getRole())) {
            manageUserService.register(account);
        } else {
            return Result.error(ResultCodeEnum.PARAM_ERROR);
        }
        return Result.success();
    }

    /**
     * 修改密码
     */
    @PutMapping("/updatePassword")
    public Result updatePassword(@RequestBody Account account) {
        if (StrUtil.isBlank(account.getUsername()) || StrUtil.isBlank(account.getPassword())
                || ObjectUtil.isEmpty(account.getNewPassword())) {
            return Result.error(ResultCodeEnum.PARAM_LOST_ERROR);
        }
        if (RoleEnum.ADMIN.name().equals(account.getRole())) {
            manageAdminService.updatePassword(account);
        }
        return Result.success();
    }

}
